package org.bobdawg.app.MALforAndroid;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener, Preference.OnPreferenceClickListener {

	public static final String KEY_TAB_PREFERENCE = "mode";
	public static final String KEY_FILTER_PREFERENCE = "filter";
	public static final String KEY_SORT_PREFERENCE = "sort";
	public static final String KEY_UPDATE_FREQ_PREFERENCE = "updateFreq";
	public static final String KEY_PRE_CACHE_INFO = "preCacheInfo";
	public static final String KEY_ABOUT_PREFERENCE = "about";
	private final static String LOG_NAME = "Preferences.java";
	//private ListPreference modeListPref; 
	private ListPreference filterListPref;
	private ListPreference sortListPref;
	private ListPreference updateFreqListPref;
	private Preference preCacheInfoPref;
	private Preference aboutPref;
	private static PackageInfo pInfo;
	GoogleAnalyticsTracker tracker;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
		try {
	    	set_pInfo(getBaseContext());
	    } catch (NameNotFoundException e) {
	    	e.printStackTrace();
	    }
		filterListPref = (ListPreference)getPreferenceScreen().findPreference(KEY_FILTER_PREFERENCE);
		sortListPref = (ListPreference)getPreferenceScreen().findPreference(KEY_SORT_PREFERENCE);
		updateFreqListPref = (ListPreference)getPreferenceScreen().findPreference(KEY_UPDATE_FREQ_PREFERENCE);
		
		preCacheInfoPref = (Preference)getPreferenceScreen().findPreference(KEY_PRE_CACHE_INFO);
		preCacheInfoPref.setOnPreferenceClickListener(this);
		
		aboutPref = (Preference)getPreferenceScreen().findPreference(KEY_ABOUT_PREFERENCE);
		aboutPref.setTitle(getBaseContext().getString(R.string.prefAboutTitle, pInfo.versionName));
		aboutPref.setSummary(R.string.prefAboutSummary);
		aboutPref.setOnPreferenceClickListener(this);
		
		// setup analytics
		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.startNewSession("UA-25348834-2", 300, this);
		
		// track page view
		tracker.trackPageView("/preferences");
		
		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		PrefChange pfChang = new PrefChange();
		prefs.registerOnSharedPreferenceChangeListener(pfChang);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		filterListPref.setSummary(getBaseContext().getString(R.string.prefViewSummary, filterListPref.getEntry()));
		sortListPref.setSummary(getBaseContext().getString(R.string.prefSortSummary, sortListPref.getEntry()));
		updateFreqListPref.setSummary(getBaseContext().getString(R.string.prefUpdateSummary, updateFreqListPref.getEntry()));
		
		// Set up a listener whenever a key changes
		getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}
	
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        // Let's do something when a preference value changes
		/*if (key.equals(KEY_TAB_PREFERENCE)) {
			tracker.trackEvent("Preference", "Changed", "Default Mode | " + modeListPref.getEntry(), 0);
			modeListPref.setSummary(getBaseContext().getString(R.string.prefModeSummary, modeListPref.getEntry()));
		} else */ if (key.equals(KEY_FILTER_PREFERENCE)) {
			tracker.trackEvent("Preference", "Changed", "Default View | " + filterListPref.getEntry(), 0);
            filterListPref.setSummary(getBaseContext().getString(R.string.prefViewSummary, filterListPref.getEntry())); 
        } else if (key.equals(KEY_SORT_PREFERENCE)) {
			tracker.trackEvent("Preference", "Changed", "Default Sort-By | " + sortListPref.getEntry(), 0);
			sortListPref.setSummary(getBaseContext().getString(R.string.prefSortSummary, sortListPref.getEntry()));
		} else if (key.equals(KEY_UPDATE_FREQ_PREFERENCE)) {
			tracker.trackEvent("Preference", "Changed", "Update Frequency | " + updateFreqListPref.getEntry(), 0);
			updateFreqListPref.setSummary(getBaseContext().getString(R.string.prefUpdateSummary, updateFreqListPref.getEntry()));
		}
		
	}
	
	@Override
	public boolean onPreferenceClick(Preference preference) {
		if(preference == aboutPref) {
			AlertDialog aboutDialog = createAboutDialog(this);
			tracker.trackEvent("Preferences","Click","About",0);
			aboutDialog.show();
			return true;
		}
		else if (preference == preCacheInfoPref) {
			Intent i = new Intent(getBaseContext(), MALManager.class);
			i.setAction(MALManager.SYNC);
			startService(i);
			return true;
		}
		// TODO Auto-generated method stub
		return false;
	}
	
	/**
	 * Try to load the package matching the name of our own package
	 * @param context
	 * @throws NameNotFoundException
	 */
	public static void set_pInfo( android.content.Context context ) throws NameNotFoundException {
		pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA);
	}
	
	public static AlertDialog createAboutDialog( android.content.Context context ) {
		String versionInfo = pInfo.versionName;

		String aboutTitle = context.getString(R.string.prefAboutDialogTitle, context.getString(R.string.app_name));
		//String versionString = context.getString(R.string.pref_about_title, versionInfo);
		String appHomepage = context.getString(R.string.app_homepage);
		String aboutText = context.getString(R.string.app_description);

		// Set up the TextView
		final android.widget.TextView message = new android.widget.TextView(context);
		//final android.text.SpannableString verString = new android.text.SpannableString(versionString);
		// We'll use a spannablestring to be able to make links clickable
		final android.text.SpannableString s = new android.text.SpannableString(aboutText);

		// Set some padding
		message.setPadding(5, 5, 5, 5);
		// Set up the final string
		message.setMovementMethod(LinkMovementMethod.getInstance());
		message.setText(Html.fromHtml("<b>Version:</b> "+ versionInfo + "<br>\n"
									+ "<b>Author:</b> BobDawg<br>\n<b>App Homepage:</b><br>\n\t<a href=\""+ appHomepage
									+ "\">bobdawg.org/android/mal.php</a>\n\n<br><br><b>Description:</b><br>" + s));
		// Now linkify the text
		//android.text.util.Linkify.addLinks(message, android.text.util.Linkify.ALL);

		return new AlertDialog.Builder(context).setTitle(aboutTitle).setCancelable(true).setIcon(R.drawable.icon).setPositiveButton(
			 context.getString(android.R.string.ok), null).setView(message).create();
	}

	@SuppressWarnings("rawtypes")
	private class ImmediateActions extends AsyncTask {

		@Override
		protected Object doInBackground(Object... arg0) {
			Looper.prepare();
			String key = (String) arg0[0];
			if (key.equals("userName") || key.equals("passwd")) {
				if (MALManager.verifyCredentials(getBaseContext())) {					
					//Toast.makeText(getBaseContext(), R.string.firstSync, Toast.LENGTH_LONG * 2).show();
					Intent i = new Intent(getBaseContext(), MALManager.class);
					i.setAction(MALManager.SYNC);
					startService(i);
				} else {
					Log.i(LOG_NAME, "verifyCredentials: failed");
				}
			} else {
				Log.i(LOG_NAME, "Credentials changed");
			}
			if (key.equals("updateFreq")) {
				Log.i(LOG_NAME, "chg sync");
				Intent i = new Intent(getBaseContext(), MALManager.class);
				i.setAction(MALManager.SCHEDULE);
				getBaseContext().startService(i);
			}
			return null;
		}
	}

	private class PrefChange implements OnSharedPreferenceChangeListener {
		@SuppressWarnings("unchecked")
		@Override
		public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
			new ImmediateActions().execute(key);			
		}

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.preferences_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		Intent i;
		switch (id) {
			case R.id.menuSync:
				i = new Intent(this, MALManager.class);
				i.setAction(MALManager.SYNC);
				startService(i);
				break;
		}
		return true;
	}

}
